package com.zzh.takeoutapp.activity;

import android.content.Intent;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.AddLocationAdapter;
import com.zzh.takeoutapp.adapter.AddressAdapter;
import com.zzh.takeoutapp.adapter.CollectOrderAdapter;
import com.zzh.takeoutapp.adapter.FoodAdapter;
import com.zzh.takeoutapp.adapter.OnRecyleItemClick;
import com.zzh.takeoutapp.adapter.SelectShopAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.config.Constants;
import com.zzh.takeoutapp.config.UrlConfig;
import com.zzh.takeoutapp.entity.SelectShopBean;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.map.LocationService;
import com.zzh.takeoutapp.model.AddressBean;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.BaseUtils;
import com.zzh.takeoutapp.utils.GsonResolve;
import com.zzh.takeoutapp.utils.LoadingUtil;
import com.zzh.takeoutapp.utils.SPUtils;
import com.zzh.takeoutapp.utils.ToolBarHelper;
import com.zzh.takeoutapp.view.goods.ViewUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/25.
 */

public class SelectShoppingAddressActivity extends BaseActivity implements
        OnGetPoiSearchResultListener {
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.assress_listview)
    RecyclerView mRecyclerView;
    @Bind(R.id.iv_showr_right)
    TextView iv_showr_right;
    @Bind(R.id.tvCity)
    TextView tvCity;
    @Bind(R.id.tv_address)
    TextView tv_address;
    @Bind(R.id.ev_text)
    AutoCompleteTextView ev_text;
    @Bind(R.id.lv_address)
    LinearLayout lv_address;
    private String address;
    private LocationService locationService;
    private PoiSearch mPoiSearch = null;
    private int loadIndex = 0;
    public List<PoiInfo> poiList;
    public final String GET_ADDRESS = "SELECT_SHOPPING_ADDRESS";
    private List<SelectShopBean> selectShopBeans;//定位的地址
    private List<SelectShopBean> selectMyShop;
    private TextView tvStickyHeaderView;
    private View stickView;
    private LoadingUtil loadingUtil;
    @Override
    public void setContent() {
        setContentView(R.layout.activity_select_shipping_address);
        ButterKnife.bind(this);
        loadingUtil= new LoadingUtil(this);
    }

    @Override
    public void initComponent() {
        selectShopBeans = new ArrayList<>();
        selectMyShop = new ArrayList<>();
        loadingUtil.startShowLoading();
        ServiceUrl.AddressServiceUrl(this, GET_ADDRESS);
        iv_showr_right.setVisibility(View.VISIBLE);
        ToolBarHelper.setTitleAndBackAndText(this, tbToolbar, "选择收货地址");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
    }

    @Override
    public void setListener() {
        address = getIntent().getStringExtra("address");
        if (address != null)
            tvCity.setText(address);
        poiList = getIntent().getParcelableArrayListExtra("poiList");
        if (poiList != null) {
            tv_address.setText(poiList.get(0).name);
        }
    }

    @Override
    public void onAfterInit() {
        /**
         * 当输入关键字变化时，动态更新建议列表
         */
        ev_text.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    return;
                }
                String keystr = ev_text.getText().toString();
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .city(address).keyword(keystr).pageNum(loadIndex));
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
        locationService = new LocationService(this);
        locationService.registerListener(mListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            selectShopBeans.removeAll(selectShopBeans);
            selectShopBeans.addAll(selectMyShop);
            for (PoiInfo info : result.getAllPoi()) {
                if (info.name != null) {
                    SelectShopBean bean = new SelectShopBean();
                    bean.setAddress(info.address);
                    bean.setKey(info.name);
                    bean.setType("附近地址");
                    bean.setLat(String.valueOf(info.location.latitude));
                    bean.setLon(String.valueOf(info.location.longitude));
                    selectShopBeans.add(bean);
                }
                setAdapter(selectShopBeans);
            }
        }
    }

    private void setAdapter(List<SelectShopBean> selectShopBeans) {
        final SelectShopAdapter addLocationAdapter = new SelectShopAdapter(selectShopBeans);
        mRecyclerView.setAdapter(addLocationAdapter);
        stickView = findViewById(R.id.stick_header);
        tvStickyHeaderView = findViewById(R.id.tv_header);
        tvStickyHeaderView.setText("我的收货地址");
        View view = new View(this);
        view.setMinimumHeight(ViewUtils.dip2px(this, 50));
        addLocationAdapter.addFooterView(view);
        addLocationAdapter.bindToRecyclerView(mRecyclerView);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View stickyInfoView = recyclerView.findChildViewUnder(stickView.getMeasuredWidth() / 2, 5);
                if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
                    tvStickyHeaderView.setText(String.valueOf(stickyInfoView.getContentDescription()));
                }
                View transInfoView = recyclerView.findChildViewUnder(stickView.getMeasuredWidth() / 2, stickView.getMeasuredHeight
                        () + 1);
                if (transInfoView != null && transInfoView.getTag() != null) {
                    int transViewStatus = (int) transInfoView.getTag();
                    int dealtY = transInfoView.getTop() - stickView.getMeasuredHeight();
                    if (transViewStatus == FoodAdapter.HAS_STICKY_VIEW) {
                        if (transInfoView.getTop() > 0) {
                            stickView.setTranslationY(dealtY);
                        } else {
                            stickView.setTranslationY(0);
                        }
                    } else if (transViewStatus == FoodAdapter.NONE_STICKY_VIEW) {
                        stickView.setTranslationY(0);
                    }
                }
            }
        });
        addLocationAdapter.notifyDataSetChanged();

        addLocationAdapter.setOnSortClick(new SelectShopAdapter.TextSortOnClickListener() {
            @Override
            public void onSortClick(View v, SelectShopBean item) {
                Intent intent = new Intent();
                intent.putExtra("getKey", item.getKey());
                SPUtils.saveString(SelectShoppingAddressActivity.this,
                        Constants.ALL_LATITUDE, item.getLat());
                SPUtils.saveString(SelectShoppingAddressActivity.this,
                        Constants.ALL_LONGITUDE, item.getLon());
                setResult(1, intent);
                finish_Activity();
            }
        });
    }


    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    /**
     * 响应城市内搜索按钮点击事件
     *
     * @param v
     */

    public void searchButtonProcess(View v) {
        String keystr = ev_text.getText().toString();
        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(address).keyword(keystr).pageNum(loadIndex));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // activity 销毁时同时销毁地图控件
        mPoiSearch.destroy();
    }

    @Override
    public void onStop() {
        EventbusHelper.unregister(this);
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    private void getdata(LatLng ll) {
        GeoCoder geoCoder = GeoCoder.newInstance();
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    return;
                }
                poiList = result.getPoiList();
                tv_address.setText(poiList.get(0).name);
                selectShopBeans.removeAll(selectShopBeans);
                selectShopBeans.addAll(selectMyShop);
                for (PoiInfo info : poiList) {
                    if (info.name != null) {
                        SelectShopBean bean = new SelectShopBean();
                        bean.setAddress(info.address);
                        bean.setKey(info.name);
                        bean.setLat(String.valueOf(info.location.latitude));
                        bean.setLon(String.valueOf(info.location.longitude));
                        bean.setType("附近地址");
                        selectShopBeans.add(bean);
                    }
                }
                setAdapter(selectShopBeans);
                locationService.stop();
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                }
            }
        };
        geoCoder.setOnGetGeoCodeResultListener(listener);
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LatLng point = new LatLng(location.getLatitude(), location.getLongitude());
                getdata(point);
            }
        }

    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case GET_ADDRESS:
                loadingUtil.stopShowLoading();
                if (jsonObject.optString("error").equals("0")) {
                    JSONObject data = jsonObject.optJSONObject("data");
                    JSONArray items = data.optJSONArray("items");
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject jsonObject1 = items.optJSONObject(i);
                        AddressBean addressBean = GsonResolve.jsonString2Bean(jsonObject1.toString(), AddressBean.class);
                        SelectShopBean bean = new SelectShopBean();
                        bean.setType("我的收货地址");
                        bean.setKey(addressBean.getAddr());
                        bean.setName(addressBean.getContact());
                        bean.setPhone(addressBean.getMobile());
                        bean.setLon(addressBean.getLng());
                        bean.setLat(addressBean.getLat());
                        selectMyShop.add(bean);
                    }
                    locationService.start();// 定位SDK
                }
                break;
        }
    }

    @OnClick({R.id.lv_address, R.id.iv_showr_right})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.lv_address:
                tv_address.setText("定位中...");
                locationService.start();// 定位SDK
                break;
            case R.id.iv_showr_right:
                Intent intent = new Intent(this, AddAddressActivity.class);
                intent.setType("MYADDRESS");
                start_Activity(intent);
                break;
        }
    }
}
